<?php
namespace app\customer\controller;
use think\Db;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
class Shopcate extends Base{
    public function qiniuupload(){
        $sysres= Db::name('system')->where('id',1)->find();
        if ($sysres['file_state']==0) {
            $file=$_FILES['file'];
            $imgpath="../public/uploads/images/";
            $imgsubpath=date('Ymd',time())."/";
            if(!file_exists($imgpath)){
                mkdir($imgpath,0777);
            }
            if(!file_exists($imgpath.$imgsubpath)){
                mkdir($imgpath.$imgsubpath,0777);
            }
            chmod($imgpath.$imgsubpath,0777);
            move_uploaded_file($file['tmp_name'],$imgpath.$imgsubpath.$file['name']);
            return json(['code' => 200, 'data' =>config('tmdhttp').$_SERVER['HTTP_HOST']."/uploads/images/".$imgsubpath.$file['name'], 'msg' => '成功']);
        }elseif($sysres['file_state']==1){
            $auth = new Auth($sysres['accesskey'],$sysres['secretkey']);
            $bucket = $sysres['bucket'];
            $token = $auth->uploadToken($bucket);
            $filePath =$_FILES['file']['tmp_name'];
            $key = $_FILES['file']['name'];
            $uploadMgr = new UploadManager();
            list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
            return json(['code' => 200, 'data' =>$sysres['url'].'/'.$_FILES['file']['name'], 'msg' => '成功']);
        }
    }
    //分类级别设置
    public function catelevel(){
        if(request()->isGet()){
            $data=Db::name('customer')->where('id',session('customer')['id'])->find();
            $this->assign('data',$data);
            return $this->fetch();
        }elseif(request()->isPost()){
            $param = input('post.');
            $data['catelevel']=$param['catelevel'];
            $res= Db::name('customer')->where(array('id'=>$param['id']))->update($data);
            if($res){
                return json(['code' => 200,'msg' => '更新成功']);
            }else{
                $cus=Db::name('customer')->where('id',session('customer')['id'])->find();
                if($cus){
                    return json(['code' => 500,'msg' => '失败']);
                }else{
                    $resin= Db::name('customer')->insert($data);
                    if($resin){
                        return json(['code' => 200,'msg' => '保存成功']);
                    }else{
                        return json(['code' => 500,'msg' => '失败']);
                    }
                }
            }
        }
    }
    public function shop_cate(){
        $catelevel=Db::name('customer')->where('id',session('customer')['id'])->find();
        $cates=Db::name('shopcate')->where('cus_id',session('customer')['id'])->where('state','<',3)->select();
        $faths=$cates;
        $cates=$this->gethtmlTree($cates, 0,0,$_SERVER['HTTP_HOST'],$catelevel['catelevel']);
        $this->assign('catelevel',$catelevel);
        $this->assign('cates',$cates);
        return $this->fetch();
    }
    private function gethtmlTree($data, $f_id,$num=0,$imgurl,$catelevel){
        $html = '';
        $num++;
        foreach($data as $k => $v)
        {
           if($v['f_id'] == $f_id)
           {         //父亲找到儿子
            $html .= '<ol>';
            $html .=    '<li>';
            $html .=        '<div class="tcate">';
            $html .=            '<div><div>';
            if ($num < $catelevel) {
                if($num==1){
                    $html .='<span class="minus">-</span><span class="plus">+</span>';
                }elseif($num==2){
                    $html .='<span style="padding-left:36px;" class="minus">-</span><span class="plus">+</span>';
                }elseif($num==3){
                    $html .='<span style="padding-left:72px;" class="minus">-</span><span class="plus">+</span>';
                }
            }else{
                $html .='<span style="display:none;" class="minus minuslast">-</span><span style="padding-left:36px;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span class="plus">+</span>';
            }
            $html .=                '</div><img src="'.$v['icon'].'">'.$v['catename'].'</h6></div>';
            $html .=            '<div>';
            if ($v['state'] == 2) {
                $html .=                '<a href="javascript:;" onClick="state_on('.$v['id'].');" style="background:#999;" class="storespan btn btn-xs">';
                $html .=                    '<input style="border:none;background:#999;color:#fff;cursor:pointer;" type="button" value="禁用">';
                $html .=                '</a>';
            }
            if ($v['state'] == 1) {
                $html .=                '<a href="javascript:;" onClick="state_on('.$v['id'].');" style="background:#5eb95e;" class="storespan btn btn-xs">';
                $html .=                    '<input style="border:none;background:#5eb95e;color:#fff;cursor:pointer;" type="button" value="启用">';
                $html .=                '</a>';
            }
            $html .=                '<a';
            if ($num < $catelevel) {
                
            }else{
                $html .=' style="display:none"';
            }
            $html .=                    ' href="javascript:;" onclick="shop_addcate(\'添加产品\',\'/index.php/customer/shopcate/shop_addcate.html?f_id='.$v['id'].'\',800,500)" class="storespan btn btn-xs">添加</a>';
            $html .=                '<a href="javascript:;"  onclick="shop_editcate(\'编辑分类\',\'/index.php/customer/shopcate/shop_editcate.html?id='.$v['id'].'\','.$v['id'].',800,500)" class="storespan btn btn-xs">编辑</a>';
            $html .=                '<a href="javascript:;" onclick="shop_delcate(this,'.$v['id'].')" class="storespan btn btn-xs">删除</a>';
            $html .=            '</div>';
            $html .=        '</div>';
            $html .= $this->gethtmlTree($data, $v['id'],$num,$imgurl,$catelevel);
            $html .=    '</li>';
            $html .= '</ol>';
           }
        }
        return $html;
    }
    public function shop_addcate(){
        if(request()->isGet()){
            $cates=Db::name('shopcate')->where('cus_id',session('customer')['id'])->where('state',1)->select();
            if(!empty(input("param.f_id"))){
                $f_id=input("param.f_id");
            }else{
                $f_id=0;
            }
            $this->assign('f_id',$f_id);
            $this->assign('cates',$cates);
            return $this->fetch();
        }elseif(request()->isPost()){
            $param=input('param.');
            $data['cus_id']=session('customer')['id'];
            $data['f_id']=$param['f_id'];
            $data['icon']=$param['icon'];
            $data['catename']=$param['catename'];
            $data['state']=1;
            $res=Db::name('shopcate')->insert($data);
            if($res){
                return json(['code' => 200,'msg' => '成功']);
            }else{
                return json(['code' => 500,'msg' => '失败']);
            }
        }
    }
    public function shop_editcate(){
        if(request()->isGet()){
            $param = input('get.');
            $data=Db::name('shopcate')->where('id',$param['id'])->find();
            $this->assign('data',$data);
            return $this->fetch();
        }elseif(request()->isPost()){
            $param = input('post.');
            // $data['f_id']=$param['f_id'];
            $data['icon']=$param['icon'];
            $data['catename']=$param['catename'];
            $data['state']=1;
            $res= Db::name('shopcate')->where(array('id'=>$param['id']))->update($data);
            if($res){
                return json(['code' => 200,'msg' => '更新成功']);
            }else{
                return json(['code' => 500,'msg' => '失败']);
            }
        }
    }
    public function state_on(){
        $id=input('param.id');
        $state = Db::name('shopcate')->where('id',$id)->find();
        if($state['state']==1){
            $status = Db::name('shopcate')->where('id',$id)->update(['state'=>2]);
            if($status){
                return json(['code' => 202,'msg' => '已禁用']);
            }
        }elseif($state['state']==2){
            $status = Db::name('shopcate')->where('id',$id)->update(['state'=>1]);
            if($status){
                return json(['code' => 201,'msg' => '已启用']);
            }
        }
        return json(['code' => 500,'msg' => '出错']);
    }
    public function shop_delcate(){
        $param = input('post.');
        $faths=Db::name('shopcate')->where('cus_id',session('customer')['id'])->where('state','<',3)->select();
        $this->delall($faths,$param['id']);
        return json(['code' => 200,'msg' => '删除成功']);

    }
    private function delall($faths,$id){
      foreach ($faths as $key => $value) {
        if ($value['id']==$id) {
            Db::name('shopcate')->where(array('id'=>$value['id']))->update(['state'=>3]);
            $s_id=Db::name('shopcate')->where('f_id',$value['id'])->where('state','<',3)->select();
            for ($i=0; $i <count($s_id) ; $i++) { 
                $this->delall($faths,$s_id[$i]['id']);
            }
        }
      }
    }
    //压缩图片并上传
    public function uploads(){
        header("Content-type: image/jpeg");
        $files=$_FILES['file'];
        $file = $files['tmp_name']; 
        $percent = 1; //图片压缩比 
        list($width, $height) = getimagesize($file); //获取原图尺寸 
        //缩放尺寸 
        $newwidth = $width * $percent; 
        $newheight = $height * $percent; 
        if(getimagesize($file)[2]==2){
           $src_im = imagecreatefromjpeg($file);
        }elseif(getimagesize($file)[2]==3){
            $src_im = imagecreatefrompng($file);
        }
        $dst_im = imagecreatetruecolor($newwidth, $newheight); 
        imagecopyresampled($dst_im, $src_im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height); 
        $imgpath="../public/uploads/images/";
        $imgsubpath=date('Ymd',time())."/";
        if(!file_exists($imgpath.$imgsubpath)){
            mkdir($imgpath.$imgsubpath,0777);
        }
        chmod($imgpath.$imgsubpath,0777);
        imagejpeg($dst_im,$imgpath.$imgsubpath.$files['name']); //输出压缩后的图片 
        imagedestroy($dst_im); 
        imagedestroy($src_im);
        return json(['code' => 200, 'data' =>"/uploads/images/".$imgsubpath.$files['name'], 'msg' => '成功']);
    }
    // 原图上传
    public function uploadtmd(){
        $sysres= Db::name('system')->where('id',1)->find();
        $photo='';
        $imgs=[];
        if ($sysres['file_state']==0) {
            $imgpath="../public/uploads/images/";
            $imgsubpath=date('Ymd',time())."/";
            if(!file_exists($imgpath)){
                mkdir($imgpath,0777);
            }
            if(!file_exists($imgpath.$imgsubpath)){
                mkdir($imgpath.$imgsubpath,0777);
            }
            chmod($imgpath.$imgsubpath,0777);
            if(isset($_FILES['file'])){
                move_uploaded_file($_FILES['file']['tmp_name'],$imgpath.$imgsubpath.$_FILES['file']['name']);
                $photo=config('tmdhttp').$_SERVER['HTTP_HOST']."/uploads/images/".$imgsubpath.$_FILES['file']['name'];
            }
            if(isset($_FILES['imgs'])){
                for ($i=0; $i <count($_FILES['imgs']['name']) ; $i++) {
                    move_uploaded_file($_FILES['imgs']['tmp_name'][$i],$imgpath.$imgsubpath.$_FILES['imgs']['name'][$i]);
                    $imgs[$i]=config('tmdhttp').$_SERVER['HTTP_HOST']."/uploads/images/".$imgsubpath.$_FILES['imgs']['name'][$i];
                }
            }
            return json(['code' => 200, 'photo' =>$photo,'imgs' =>implode(",",$imgs), 'msg' => '成功']);
        }elseif($sysres['file_state']==1){
            $auth = new Auth($sysres['accesskey'],$sysres['secretkey']);
            $uploadMgr = new UploadManager();
            if(isset($_FILES['file'])&&!isset($_FILES['imgs'])){
                $bucket = $sysres['bucket'];
                $token = $auth->uploadToken($bucket);
                $filePath =$_FILES['file']['tmp_name'];
                $key = $_FILES['file']['name'];
                list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
                $photo=$sysres['url'].'/'.$_FILES['file']['name'];
                return json(['code' => 200, 'photo' =>$photo, 'msg' => '成功']);
            }
            if(isset($_FILES['imgs'])&&!isset($_FILES['file'])){
                for ($i=0; $i <count($_FILES['imgs']['name']) ; $i++) {
                    $bucket[$i] = $sysres['bucket'];
                    $token[$i] = $auth->uploadToken($bucket[$i]);
                    $filePath[$i] =$_FILES['imgs']['tmp_name'][$i];
                    $key[$i] = $_FILES['imgs']['name'][$i];
                    list($ret, $err) = $uploadMgr->putFile($token[$i], $key[$i], $filePath[$i]);
                    $imgs[$i]=$sysres['url'].'/'.$_FILES['imgs']['name'][$i];
                }
                return json(['code' => 200,'imgs' =>implode(",",$imgs), 'msg' => '成功']);
            }
            if(isset($_FILES['imgs'])&&isset($_FILES['file'])){
                array_push($_FILES['imgs']['error'],$_FILES['file']['error']);
                array_push($_FILES['imgs']['name'],$_FILES['file']['name']);
                array_push($_FILES['imgs']['size'],$_FILES['file']['size']);
                array_push($_FILES['imgs']['tmp_name'],$_FILES['file']['tmp_name']);
                array_push($_FILES['imgs']['type'],$_FILES['file']['type']);
                $count=count($_FILES['imgs']['name']);
                for ($i=0; $i <count($_FILES['imgs']['name']) ; $i++) {
                    $bucket[$i] = $sysres['bucket'];
                    $token[$i] = $auth->uploadToken($bucket[$i]);
                    $filePath[$i] =$_FILES['imgs']['tmp_name'][$i];
                    $key[$i] = $_FILES['imgs']['name'][$i];
                    list($ret, $err) = $uploadMgr->putFile($token[$i], $key[$i], $filePath[$i]);
                    $imgs[$i]=$sysres['url'].'/'.$_FILES['imgs']['name'][$i];
                }
                $photo=$sysres['url'].'/'.$_FILES['imgs']['name'][$count-1];
                array_splice($imgs,$count-1,1);
                return json(['code' => 200, 'photo' =>$photo,'imgs' =>implode(",",$imgs), 'msg' => '成功']);
            }
        }
    }
}
